﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RuoVea.ExUtil;

/// <summary>
/// 描 述：类型转换扩展
/// </summary>
public static partial class Extensions
{
    #region 数值转换

    /// <summary>
    /// 转换为整型
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>整型类型数据</returns>
    public static int ToInt(this object data)
    {
        if (data == null)
            return 0;
        int result;
        var success = int.TryParse(data.ToString(), out result);
        if (success)
            return result;
        try
        {
            return Convert.ToInt32(ToDouble(data, 0));
        }
        catch (Exception)
        {
            return 0;
        }
    }

    /// <summary>
    /// 转换为可空整型
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>可空整型数据</returns>
    public static int? ToIntOrNull(this object data)
    {
        if (data == null)
            return null;
        int result;
        bool isValid = int.TryParse(data.ToString(), out result);
        if (isValid)
            return result;
        return null;
    }

    /// <summary>
    /// 转换为双精度浮点数
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>整型数据</returns>
    public static double ToDouble(this object data)
    {
        if (data == null)
            return 0;
        double result;
        return double.TryParse(data.ToString(), out result) ? result : 0;
    }

    /// <summary>
    /// 转换为双精度浮点数,并按指定的小数位4舍5入
    /// </summary>
    /// <param name="data">数据</param>
    /// <param name="digits">小数位数</param>
    /// <returns>按指定的小数位4舍5入双精度浮点数</returns>
    public static double ToDouble(this object data, int digits)
    {
        return Math.Round(ToDouble(data), digits);
    }

    /// <summary>
    /// 转换为可空双精度浮点数
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>可空双精度浮点数</returns>
    public static double? ToDoubleOrNull(this object data)
    {
        if (data == null)
            return null;
        double result;
        bool isValid = double.TryParse(data.ToString(), out result);
        if (isValid)
            return result;
        return null;
    }

    /// <summary>
    /// 转换为高精度浮点数
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>高精度浮点数</returns>
    public static decimal ToDecimal(this object data)
    {
        if (data == null)
            return 0;
        decimal result;
        return decimal.TryParse(data.ToString(), out result) ? result : 0;
    }

    /// <summary>
    /// 转换为高精度浮点数,并按指定的小数位4舍5入
    /// </summary>
    /// <param name="data">值</param>
    /// <param name="digits">小数位数</param>
    /// <returns>按指定的小数位4舍5入双精度浮点数</returns>
    public static decimal ToDecimal(this object data, int digits)
    {
        return Math.Round(ToDecimal(data), digits);
    }

    /// <summary>
    /// 转换为可空高精度浮点数
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>可空高精度浮点数</returns>
    public static decimal? ToDecimalOrNull(this object data)
    {
        if (data == null)
            return null;
        decimal result;
        bool isValid = decimal.TryParse(data.ToString(), out result);
        if (isValid)
            return result;
        return null;
    }

    /// <summary>
    /// 转换为可空高精度浮点数,并按指定的小数位4舍5入
    /// </summary>
    /// <param name="data">数据</param>
    /// <param name="digits">小数位数</param>
    /// <returns>按指定的小数位4舍5入双精度浮点数</returns>
    public static decimal? ToDecimalOrNull(this object data, int digits)
    {
        var result = ToDecimalOrNull(data);
        if (result == null)
            return null;
        return Math.Round(result.Value, digits);
    }

    #endregion

    #region 日期转换
    /// <summary>
    /// 转换为日期
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>日期数据</returns>
    public static DateTime ToDate(this object data)
    {
        if (data == null)
            return DateTime.MinValue;

        DateTime result;
        bool isValid = DateTime.TryParse(data.ToString(), out result);

        if (isValid) return result;
        else
        {
            isValid = DateTime.TryParseExact(data.ToString(), "yyyyMMdd", null, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out result);
            if (isValid) return result;
            else return DateTime.MinValue;
        }
    }

    /// <summary>
    /// 转换为可空日期
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>可空日期数据</returns>
    public static DateTime? ToDateOrNull(this object data)
    {
        if (data == null)
            return null;
        DateTime result;
        bool isValid = DateTime.TryParse(data.ToString(), out result);
        if (isValid)
            return result;
        else
        {
            isValid = DateTime.TryParseExact(data.ToString(), "yyyyMMdd", null, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out result);
            if (isValid) return result;
            else return null;
        }
    }

    #endregion

    #region 布尔转换
    /// <summary>
    /// 转换为布尔值
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>布尔值</returns>
    public static bool ToBool(this object data)
    {
        if (data == null)
            return false;
        bool? value = GetBool(data);
        if (value != null)
            return value.Value;
        bool result;
        return bool.TryParse(data.ToString(), out result) && result;
    }

    /// <summary>
    /// 获取布尔值
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>可空布尔值</returns>
    private static bool? GetBool(this object data)
    {
        switch (data.ToString().Trim().ToLower())
        {
            case "0":
                return false;
            case "1":
                return true;
            case "是":
                return true;
            case "否":
                return false;
            case "yes":
                return true;
            case "no":
                return false;
            default:
                return null;
        }
    }

    /// <summary>
    /// 转换为可空布尔值
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>可空布尔值</returns>
    public static bool? ToBoolOrNull(this object data)
    {
        if (data == null)
            return null;
        bool? value = GetBool(data);
        if (value != null)
            return value.Value;
        bool result;
        bool isValid = bool.TryParse(data.ToString(), out result);
        if (isValid)
            return result;
        return null;
    }

    #endregion

    #region 字符串转换
    /// <summary>
    /// 转换为字符串
    /// </summary>
    /// <param name="data">值</param>
    /// <returns>字符串</returns>
    public static string ToString(this object data)
    {
        return data == null ? string.Empty : data.ToString().Trim();
    }

    /// <summary>
    /// 获取对象值
    /// </summary>
    /// <param name="data">值</param>
    /// <param name="name">字段名</param>
    /// <returns>对象值</returns>
    public static object GetObject(this object data, string name)
    {
        return data.GetType().GetProperty(name)?.GetValue(data);
    }

    /// <summary>
    /// 获取字符串
    /// </summary>
    /// <param name="data">值</param>
    /// <param name="name">字段名</param>
    /// <returns>字符串</returns>
    public static string GetString(this object data, string name)
    {
        return data.GetType().GetProperty(name)?.GetValue(data)?.ToString();
    }

    #endregion

    #region string 转 byte[]
    /// <summary>
    /// string 转 byte[]
    /// </summary>
    /// <param name="str">字符串</param>
    /// <returns>byte数组</returns>
    public static byte[] GetBytes(this string str)
    {
        byte[] bytTemp = System.Text.Encoding.UTF8.GetBytes(str);
        return bytTemp;
    }
    #endregion

    #region byte[] 转 string
    /// <summary>
    ///  byte[] 转 string
    /// </summary>
    /// <param name="bytes">byte数组</param>
    /// <returns>字符串</returns>
    public static string GetString(this byte[] bytes)
    {
        char[] chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }
    #endregion

    #region 字典扩展
    /// <summary>
    /// 将一个字典转化为 QueryString
    /// </summary>
    /// <param name="dict">字典值</param>
    /// <param name="urlEncode">是否UrlEncode编码</param>
    /// <returns>字符串</returns>
    public static string ToQueryString(this Dictionary<string, string> dict, bool urlEncode = true)
    {
        return string.Join("&", dict.Select(p => $"{(urlEncode ? p.Key?.UrlEncode() : "")}={(urlEncode ? p.Value?.UrlEncode() : "")}"));
    }

    /// <summary>
    /// 将一个字符串 URL 编码
    /// </summary>
    /// <param name="str">字符串</param>
    /// <returns>编码后的字符串</returns>
    public static string UrlEncode(this string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return "";
        }
        return System.Web.HttpUtility.UrlEncode(str, Encoding.UTF8);
    }

    /// <summary>
    /// 移除空值项
    /// </summary>
    /// <param name="dict">字典</param>
    public static void RemoveEmptyValueItems(this Dictionary<string, string> dict)
    {
        dict.Where(item => string.IsNullOrEmpty(item.Value)).Select(item => item.Key).ToList().ForEach(key =>
        {
            dict.Remove(key);
        });
    }
    #endregion
}
